/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controlador;

import dominio.UsuarioMd;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import util.Controlador;
import util.NivelAcesso;
import util.Seguranca;

/**
 *
 * @author Bughi
 */
@WebServlet(name = "IntranetFt", urlPatterns = {"/intranet/*"},
initParams = {
    @WebInitParam(name = "usuario", value = "controlador.UsuarioCt"),
    @WebInitParam(name = "login", value = "controlador.LoginCt"),
    @WebInitParam(name = "grupo", value = "controlador.GrupoUsuarioCt"),
    @WebInitParam(name = "departamento", value = "controlador.DepartamentoCt"),
    @WebInitParam(name = "compromisso", value = "controlador.CompromissoCt"),
    @WebInitParam(name = "acervo", value = "controlador.AcervoCt"),
    @WebInitParam(name = "site", value = "controlador.SiteCt"),})
public class IntranetFt extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setAttribute("baseURL", getServletContext().getContextPath());
        String caminho = request.getRequestURI();
        int pos1 = caminho.lastIndexOf("/");
        int pos2 = caminho.lastIndexOf("/", pos1 - 1);

        String modulo = caminho.substring(pos2 + 1, pos1);
        String acao = caminho.substring(pos1 + 1, caminho.length());

        String className = getInitParameter(modulo);
        try {
            Class<Controlador> classControlador = (Class<Controlador>) Class.forName(className);
            Constructor<Controlador> construtorControlador = classControlador.getConstructor(HttpServletRequest.class, HttpServletResponse.class, ServletContext.class);
            Controlador controlador = construtorControlador.newInstance(request, response, getServletContext());
            Class[] parameters = new Class[0];
            Method metodo = controlador.getClass().getDeclaredMethod(acao, parameters);

            if (metodo == null) {
                metodo = controlador.getClass().getDeclaredMethod("padrao", parameters);
            }

            Seguranca seg = metodo.getAnnotation(Seguranca.class);

            //se existe restricao de acesso
            if (seg != null) {
                UsuarioMd usuario = (UsuarioMd) request.getSession().getAttribute("usuario");
                if (usuario != null) {                                     
                    
                    if (!temAcesso(seg.nivel(), NivelAcesso.valueOf(usuario.getGrupo().getNome()))){
                    //if (!seg.nivel().toString().contains(usuario.getGrupo().getNome())){
                    //if (!usuario.getGrupo().getNome().(seg.nivel().toString())) {
                        metodo = controlador.getClass().getDeclaredMethod("padrao", parameters);
                    }

                } else {
                    metodo = controlador.getClass().getDeclaredMethod("padrao", parameters);
                }

            }

            metodo.invoke(controlador);
            controlador.responder();

        } catch (Exception e) {
            PrintWriter pw = response.getWriter();
            pw.write(acao + "<br>");
            pw.write(modulo + "<br>");
            pw.write(caminho + "<br>");
            pw.write(e.getMessage() + "<br>");
        }

        //agendaJava/agenda.java/contato/listar
        //"/agendaJava/agenda/contato/listar"
        /*
         * AgendaCt controlador = new
         * AgendaCt(request,response,getServletContext()); String acao =
         * controlador.getParameterValue("acao") != null ?
         * controlador.getParameterValue("acao") : "padrao"; try { Class[]
         * parameters = new Class[0]; Method metodo =
         * controlador.getClass().getDeclaredMethod(acao, parameters);
         * metodo.invoke(controlador); controlador.responder(); } catch
         * (Exception ex) { //NoSuchMethodException | SecurityException //Acao
         * não encontrada
         * Logger.getLogger(IntranetFt.class.getName()).log(Level.SEVERE, null,
         * ex); }
         */
    }
    
    private boolean temAcesso(NivelAcesso[] nivel,NivelAcesso atual){
        for (NivelAcesso acesso:nivel){
            if (acesso == atual){
                return true;
            }
        }
        return false;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
